import requests
import re
import csv
import time
header = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 OPR/80.0.4170.63'}
Request = requests.get('https://www.huya.com/g/lol', headers=header)
result = Request.text

image = re.findall(r'<img class="pic" data-original="(.*?)"', result)


title = re.findall(r'<a href=".*" class="title" title=".*" target="_blank">(.*)</a>', result)


name = re.findall(r'<i class="nick" title=".*">(.*)</i>', result)
# print(name)

persron = re.findall(r'<i class="js-num">(.*)</i>', result)



score = re.findall(r'<a href="https://www\.huya\.com/(.*)" class="title" title=".*" target="_blank">.*</a>', result)






# for m in range(len(image)):
#     if re.match(r'https://', image[m]):
#         print(image[m])
dict_list = [['标题', '名字', '人气', '分数', '图片']]


items = []

# 用字典保存直播间信息
for i in range(len(image)):
    dict_ = {'title': '', 'name': '', 'persron': '', 'score': '','image':''}

    # 加match主要是去除无效链接
    if(re.match(r'https://',image[i])):
        dict_['title'] = title[i]
        dict_['name'] = name[i]
        dict_['persron'] = persron[i]
        dict_['score'] = score[i]
        dict_['image'] = image[i]
        items.append(dict_)

# dc={}
# for i in items:
#     dc.update(i)
#     sd_list=[dc.get('title'),dc.get('name'),dc.get('persron'),dc.get('score'),dc.get('image')]
#     dict_list.append(sd_list)
# print(dict_list)

# for n in dict_list:
#     with open('sdf.csv','a',encoding="utf-8-sig",newline='') as g:
#         csv_=csv.writer(g,dialect='excel')
#         csv_.writerow(n)
#
for o in items:
    name=o['name']
    persron=o['persron']
    title=o['title']
    score=o['score']
    image=o['image']
    ok_list=[title,name,persron,score,image]
    dict_list.append(ok_list)
    print(ok_list)

for j in dict_list:
    with open('asda.csv','a',encoding='utf-8-sig',newline='') as k:
        fgc=csv.writer(k,'excel')
        fgc.writerow(j)
# title = items[0]
# print(title)

# name = items[1]
# persron = items[2]
# score = items[3]
# image = items[4]
# for m in i:
#     print('aa')
#     alist_ = []
#     alist_.extend([title[m], name[m], persron[m], score[m], image[m]])
#     dict_list.append(alist_)
#     print(dict_list)




# for m in items:
#     print(m)



# title = dict_['title']
# name = dict_['name']
# persron = dict_['persron']
# score = dict_['score']
# image = dict_['href']
#
#
#
#
#
#
#






